import { Scan } from '@nutui/icons-react-taro';
import {
  Button,
  Cell,
  Loading,
  NumberKeyboard,
  Overlay,
  Popup,
  SearchBar,
  Table,
  Tag,
} from '@nutui/nutui-react-taro';
import { View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useCountDown, useRequest } from 'ahooks';
import { useMemo, useState } from 'react';
import {
  getDianchiDetailApi,
  getDianchiList,
  openDoorApi,
} from '../../../servers/servers';
import './index.less';

const jiebangdianchi = () => {
  const {
    runAsync,
    data: batteryList,
    loading,
  } = useRequest(
    async (battery) => {
      if (!battery) {
        return [];
      }
      // 至少输入5个字符
      if (battery?.length < 6) {
        Taro.showToast({
          title: '请最少输入6位电池编码',
          icon: 'none',
          duration: 5000,
        });

        return [];
      }

      const _res = await getDianchiList(
        {
          id: battery,
          // status: 1,
        },
        true,
      );

      return _res?.data;
    },
    {
      debounceWait: 300,
      manual: true,
    },
  );

  // const [details, setDatails] = useState([]);

  const [cabinetId, setcabinetId] = useState('');

  /* 状态 */
  const [status, setStatus] = useState(1);

  /* 查看详情 */
  const { data: details, runAsync: getDianchiDetailRun } = useRequest(
    async (_data) => {
      Taro.showLoading({
        title: '加载中...',
      });
      const _res = await getDianchiDetailApi({
        ..._data,
      });
      Taro.hideLoading();

      console.log('_res_res_res_res', _res);
      return _res?.data ?? [];
    },
    {
      manual: true,
      /* 轮询 */
      pollingInterval: 20000,
    },
  );

  // 判断当前换电柜是否支持开门
  const isAllDisable = useMemo(() => {
    if (!details || details?.length === 0) {
      return false;
    }

    const lists = [];

    // _item?.batteryId ||
    //                     _item?.ifDisabled ||
    //                     _item?.ifOpened ||
    //                     _item?.ifFault ||

    details.forEach((_e) => {
      if (!_e?.batteryId && !_e?.ifDisabled && !_e.ifOpened && !_e.ifFault) {
        lists.push(_e);
      }
    });

    console.log('listslistslistslists', lists);
    return lists.length > 2 ? true : false;
  }, [details]);

  const [searchValue, setSearchValue] = useState('');

  const [open, setOpen] = useState(false);

  const WrapperStyle = {
    display: 'flex',
    height: '100%',
    alignItems: 'center',
    justifyContent: 'center',
  };

  const columns = [
    {
      title: '电柜信息',
      key: 'cabinetId',
      render: (_record) => {
        return (
          <div>
            {_record?.cabinetId}（{_record?.cabinetAddress}）
          </div>
        );
      },
      width: '500rpx'
    },
    {
      title: '',
      key: 'na121212me',
      width: 110,
      render: (_record, index) => {
        return (
          <Button
            type="default"
            onClick={async () => {
              setOpen(true);
              // setViweUser(_record?.name);
              getDianchiDetailRun({
                cabinetId: _record?.cabinetId,
              });
              setcabinetId(_record?.cabinetAddress);
              setStatus(_record?.cabinetStatus);
              // setDatails({
              //   ..._record,
              // });
            }}
          >
            查看详情
          </Button>
        );
      },
    },
  ];

  const { runAsync: openDoorRun, loading: openDoorLoading } = useRequest(
    async (_data) => {
      const { msg = '' } = await openDoorApi({
        ..._data,
      });
    },
    {
      manual: true,
    },
  );

  const [refeBtnLoading, setRefeBtnLoading] = useState(false);

  const [targetDate, setTargetDate] = useState();

  const [countdown] = useCountDown({
    targetDate,
    onEnd: () => {
      // alert('End of the time');
    },
  });

  const [visible, setVisible] = useState(false);
  const onChange = (number) => {
    console.log(`输入：${number}`);
    setSearchValue(`${searchValue}${number}`);
  };
  const onDelete = () => {
    console.log('删除');
  };

  return (
    <div className="batterystatus_box">
      <Overlay visible={loading}>
        <div className="wrapper" style={WrapperStyle}>
          <Loading direction="vertical">加载中...</Loading>
        </div>
      </Overlay>

      <SearchBar
        readOnly
        onInputClick={() => {
          console.log('点击了');
          setVisible(true);
        }}
        autoFocus
        style={{
          '--nutui-searchbar-input-height': '100rpx',
        }}
        onChange={(_val) => {
          setSearchValue(_val);
        }}
        value={searchValue}
        left={
          <Scan
            onClick={() => {
              // 允许从相机和相册扫码
              Taro.scanCode({
                scanType: 'qrCode',
                success: (res) => {
                  const pattern = /BT.*$/;

                  const match = res?.result?.match(pattern);
                  if (match) {
                    setSearchValue(match?.[0]);
                  } else {
                    Taro.showToast({
                      title: '请扫描正确的二维码',
                      icon: 'none',
                      duration: 2000,
                    });
                  }

                  console.log(res);
                },
                errMsg: (_res) => {
                  console.log(_res);
                },
              });
            }}
          />
        }
        placeholder="输入换电柜编码后6位进行搜索"
        right={
          <Button
            type="primary"
            onClick={() => {
              runAsync(searchValue);
            }}
          >
            搜索
          </Button>
        }
        onSearch={(vales) => {
          runAsync(vales);
        }}
      />

      {/* <Cell title="默认键盘" onClick={() => setVisible(true)} /> */}
      <NumberKeyboard
        visible={visible}
        onChange={onChange}
        onDelete={onDelete}
        onClose={() => setVisible(false)}
      />

      <Table columns={columns} data={batteryList} className='battert_table' />

      <Popup
        lockScroll={false}
        destroyOnClose
        visible={open}
        position="right"
        style={{ height: '100%', width: '95%', overflow: 'scroll' }}
        onClose={() => {
          setOpen(false);
        }}
      >
        <View
          className="at-article__h5"
          style={{
            paddingTop: 10,
            paddingBottom: 10,
            display: 'flex',
            marginLeft: '20rpx',
            flexDirection: 'column',
          }}
        >
          {/* isAllDisable */}
          {!isAllDisable && (
            <View
              className="at-article__p"
              style={{
                marginLeft: 0,
                color: 'red',
              }}
            >
              当前电柜的可用仓少于2个，不允许开仓
            </View>
          )}

          <View
            className="at-article__p"
            style={{
              marginLeft: 0,
            }}
          >
            换电柜编号： {details?.[0]?.cabinetId}
          </View>
          <View
            className="at-article__p"
            style={{
              marginLeft: 0,
            }}
          >
            换电柜地址： {cabinetId}
          </View>
          <View
            className="at-article__p"
            style={{
              marginLeft: 0,
              color: status === '1' ? 'green' : 'red',
            }}
          >
            换电柜状态： {status === '1' ? '正常运行' : '离线'}
          </View>

          <Button
            block
            type="primary"
            style={{
              marginLeft: '10%',
              width: '80%',
              marginTop: 10,
            }}
            loading={refeBtnLoading}
            onClick={async () => {
              // const _res = await runAsync(searchValue);
              setRefeBtnLoading(true);
              setTargetDate(Date.now() + 10000);

              await getDianchiDetailRun({
                cabinetId: details?.[0]?.cabinetId,
              });
              setTimeout(() => {
                setRefeBtnLoading(false);
              }, 10000);
            }}
          >
            刷新 {countdown > 0 && Math.round(countdown / 1000)}
          </Button>
        </View>
        {/* 换电柜编号：{details?.[0]?.cabinetId} */}
        {details?.map((_item) => {
          return (
            <Cell.Group
              key={_item.cabinId}
              style={{
                marginLeft: '20rpx',
                marginRight: '20rpx',
                border: '1px solid #DFE2EB',
                borderRadius: '24rpx',
                marginBottom: 12,
                '--nutui-cell-group-wrap-margin': '0',
              }}
              divider={false}
            >
              <Cell
                style={{
                  paddingTop: 0,
                  paddingBottom: 0,
                }}
                title={
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      paddingTop: 0,
                    }}
                  >
                    <div>
                      仓门 {_item?.cabinId}
                      {/* 故障 */}
                      {_item?.ifFault && (
                        <Tag
                          style={{
                            marginLeft: 15,
                          }}
                          type="danger"
                        >
                          故障
                        </Tag>
                      )}
                      {/* 禁用 */}
                      {_item?.ifDisabled && (
                        <Tag
                          style={{
                            marginLeft: 15,
                          }}
                          type="danger"
                        >
                          禁用
                        </Tag>
                      )}
                      {/* 已开门 */}
                      {_item?.ifOpened && (
                        <Tag
                          style={{
                            marginLeft: 15,
                          }}
                          type="warning"
                        >
                          已开门
                        </Tag>
                      )}
                      {/* 仓门状态 */}
                      {!_item?.batteryId &&
                        _item?.ifDisabled &&
                        _item?.ifOpened &&
                        _item?.ifFault && (
                          <Tag
                            style={{
                              marginLeft: 15,
                            }}
                            type={'success'}
                          >
                            仓门状态：正常
                          </Tag>
                        )}
                    </div>

                    {!_item?.batteryId &&
                      !_item?.ifDisabled &&
                      !_item?.ifOpened &&
                      !_item?.ifFault &&
                      isAllDisable && (
                        <Button
                          shape="square"
                          type="primary"
                          size="mini"
                          style={{
                            borderRadius: 8,
                          }}
                          // 有电池，就不是空仓，禁用
                          disabled={
                            _item?.batteryId ||
                            _item?.ifDisabled ||
                            _item?.ifOpened ||
                            _item?.ifFault ||
                            !isAllDisable
                          }
                          onClick={() => {
                            Taro.showModal({
                              title: '提示',
                              content: '确定要开启仓门吗？',
                              success: async (res) => {
                                if (res.confirm) {
                                  try {
                                    Taro.showLoading({
                                      title: '开仓中...',
                                      mask: true,
                                    });

                                    await openDoorRun({
                                      cabinetId: _item?.cabinetId,
                                      doorNumber: _item?.cabinId,
                                    });

                                    setTimeout(() => {
                                      Taro.hideLoading();

                                      getDianchiDetailRun({
                                        cabinetId: _item?.cabinetId,
                                      });

                                      Taro.showToast({
                                        title: '开仓成功',
                                        icon: 'success',
                                        duration: 2000,
                                      }); //CHZD12KPD0220715116
                                    }, 5000);
                                  } catch (error) {
                                    console.log('error', error);
                                    Taro.hideLoading();
                                  }
                                }
                              },
                            });
                          }}
                        >
                          打开仓门
                        </Button>
                      )}
                  </div>
                }
              />
              <Cell
                style={{
                  paddingTop: 3,
                  paddingBottom: 0,
                }}
              >
                <div>
                  {/* 是否禁用 */}

                  {/* <Space wrap> */}
                  {/* enableStatus为0就是禁用 */}
                  {/* <Tag
                      type={+_item?.enableStatus === '0' ? 'danger' : 'success'}
                    >
                      仓门状态：{+_item?.enableStatus === '0' ? '禁用' : '正常'}
                    </Tag> */}

                  {/* doorStatus为0就是空仓 */}
                  {/* <Tag type={+_item?.doorStatus === 0 ? 'success' : 'danger'}>
                      是否空仓：{+_item?.doorStatus === 0 ? '是' : '否'}
                    </Tag>
                  </Space> */}

                  <View
                    className="at-article__p"
                    style={{
                      marginLeft: 0,
                      marginTop: 0,
                    }}
                  >
                    电池编码：{_item?.batteryId ? _item?.batteryId : '空仓'}
                  </View>
                </div>
              </Cell>
            </Cell.Group>
          );
        })}
      </Popup>
    </div>
  );
};

export default jiebangdianchi;
